import java.io.*;
import java.text.ParseException;
import java.util.*;

public class Catalog 
{

	public Catalog(String catalogFilename) throws NumberFormatException, ParseException 
	{
		
		this.catalogFilename = catalogFilename;
		File file = new File(catalogFilename);
		try{
			Scanner scanner = new Scanner (file);
			
			while (scanner.hasNextLine())
			{
				String line = scanner.nextLine();
				Item item;
				if(line.startsWith("V"))
					item = new Video(line);
				else
					item = new Book(line);
				this.libraryCatalog.put(item.getId(), item);
			}     
			scanner.close();
		}
		catch (FileNotFoundException e)
		{
			e.printStackTrace();
		}     
	}
	
	public void persistCatalogItems() throws IOException
	{ 
		File catalogFile = new File(this.catalogFilename);
		FileWriter fWriter = new FileWriter(catalogFile);
		BufferedWriter writer = new BufferedWriter(fWriter);
		
		for (Map.Entry<String, Item> entry : libraryCatalog.entrySet())
		{
			Item item = entry.getValue();
			String line = item.serializeItem();
			writer.write(line);
			writer.newLine();
		}
		
		writer.close();	
	}
	
	public ArrayList<Item> findItems(String searchQuery)
	{
		
		ArrayList<Item> results = new ArrayList<Item>();
		
		for (Map.Entry<String, Item> entry : libraryCatalog.entrySet())
		{
			Item item = entry.getValue();
			if(item.containsString(searchQuery))
				results.add(item);
		}
		return results;
	}
	
	public Map<String, Integer> totalNoOfBooksAndVideosinLibrary()
	{
		Map<String, Integer> itemCountsByCategory = new HashMap<String, Integer>();
		for (Map.Entry<String, Item> entry : libraryCatalog.entrySet())
		{
			Item item = entry.getValue();
			String category = item.getCategory();
			
			if(!itemCountsByCategory.containsKey(category))
			{
				itemCountsByCategory.put(category, 1);
			}
			else
			{
				Integer currentCount = itemCountsByCategory.get(category);
				itemCountsByCategory.put(category, ++currentCount);
			}
		}
		
		return itemCountsByCategory;
	}
			
	public boolean isAValidItem(String itemId)
	{
		if(libraryCatalog.containsKey(itemId))
			return true;
		return false;
	}
	
	public Item getItem(String itemId)
	{
		return this.libraryCatalog.get(itemId);
	}
		
	public int getNoOfItemsBorrowed()
	{
		int totalBorrowedCount = 0;
		for (Map.Entry<String, Item> entry : libraryCatalog.entrySet())
		{
			Item item = entry.getValue();

			if(item.isAvailableForReserve())
				++totalBorrowedCount;
		}

		return totalBorrowedCount;
	}
	
	Map<String, Item> libraryCatalog = new HashMap<String, Item>();
	String catalogFilename;
}
